package com.otogami.server.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.apache.commons.lang.NotImplementedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.otogami.server.model.VideogameEntity;

public class VideogameDatabaseDao implements VideogameDao {

	private final static Logger LOG = LoggerFactory.getLogger(VideogameDatabaseDao.class);

	@Override
	public VideogameEntity findById(Long id) {
		throw new NotImplementedException("The medthod findById(Long id) is not yet implemented.");
	}

	@Override
	public VideogameEntity findByStoreGameId(String storeId, String id) {
		throw new NotImplementedException("The medthod findByStoreGameId(String storeId, String id) is not yet implemented.");
	}

	@Override
	public List<VideogameEntity> findByPlatform(String platform) {
		throw new NotImplementedException("The medthod findByPlatform(String platform) is not yet implemented.");
	}

	@Override
	public void update(List<VideogameEntity> videogameList) {
		LOG.info("Updating {} videogames" + videogameList.size());
		EntityManager em = createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();

		int count = 0;
		for (VideogameEntity videogameEntity : videogameList) {
			LOG.info("Persisting " + videogameEntity);
			em.persist(videogameEntity);

			if (++count % 20 == 0) {
				// flush a batch of updates and release memory:
				em.flush();
				em.clear();
			}
		}

		tx.commit();
		em.close();
	}

	@Override
	public void findAll() {
		LOG.info("findAll()");
		EntityManager em = createEntityManager();
		List<VideogameEntity> videogames = em.createQuery("select b from videogame b").getResultList();
		LOG.info("Number of videogames found: " + videogames.size());
		for (VideogameEntity videogameEntity : videogames) {
			LOG.info(videogameEntity.toString());
		}
		em.close();

		LOG.info("FUNCIONAAAAAAAAA");
	}

	private EntityManager createEntityManager() {
		return Persistence.createEntityManagerFactory("videogame").createEntityManager();
	}

}
